package com.atguigu.security;

import com.atguigu.pojo.User;
import com.atguigu.util.MD5Utils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    //模拟数据库中的用户数据
    static Map<String, User> map =   new HashMap<String, User>();

    static {
        com.atguigu.pojo.User user1 =  new com.atguigu.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("admin");
        user1.setTelephone("123");

        com.atguigu.pojo.User user2 =  new com.atguigu.pojo.User();
        user2.setUsername("zhangsan");
        user2.setPassword("123");
        user2.setTelephone("321");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }


    //登录(根据前端传入的用户名查询用户信息，给springsecurity框架)
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = map.get(username);
        if (user == null){
            return null;
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                authorities.add(new SimpleGrantedAuthority("delete"));
                authorities.add(new SimpleGrantedAuthority("add"));
                authorities.add(new SimpleGrantedAuthority("query"));
                String password = user.getPassword();
             //   String pwd = MD5Utils.md5(password);
                 String pwd = new BCryptPasswordEncoder().encode(password);

        return new org.springframework.security.core.userdetails.User(user.getUsername(),pwd,authorities );
    }
}
